<?php

class AcessoController extends Zend_Controller_Action {

    public function init() {
        
    }

    public function indexAction() {
        $this->_helper->viewRenderer->setNoRender();
        $this->redirect('/acesso/login');
    }

    public function loginAction() {
        if (!is_null($this->getParam('login')) && !is_null($this->getParam('password'))) {
            $tUsuario = new DbTable_Usuario();

            $usuario = $tUsuario->fetchAll(array("email = (?)" => $this->getParam('login'),
                        "senha = (?)" => $this->getParam('password')))->current();

            $sessionRole = new Zend_Session_Namespace('role');

            $tipoUsuario = $usuario->Perfil_id;

            if (is_null($tipoUsuario)) {
                $this->redirect('/acesso/login/invalido/true');
            } elseif ($tipoUsuario == TipoUsuario::ADMINISTRADOR) {
                Zend_Registry::set('perfilCorrente', 'ADMINISTRADOR');
            } elseif ($tipoUsuario == TipoUsuario::USUARIO) {
                Zend_Registry::set('perfilCorrente', 'CLIENTE');
            }
            $sessionRole->usuario = serialize($usuario);
            $sessionRole->idUsuario = $usuario->id;
            $sessionRole->role = Zend_Controller_Action_HelperBroker::getStaticHelper('role')->nameToAlias(Zend_Registry::get('perfilCorrente'));
            $this->redirect('/index');
        }

        if (!is_null($this->_getParam('invalido')))
            $this->view->message = Messages::LOGIN_USUARIO_INCORRETO;
        elseif (!is_null($this->_getParam('semacesso')))
            $this->view->message = Messages::LOGIN_USUARIO_SEM_ACESSO;
    }

    public function logoutAction() {
        $this->_helper->viewRenderer->setNoRender();
        $sessionRole = new Zend_Session_Namespace('role');
        $sessionRole->role = Zend_Controller_Action_HelperBroker::getStaticHelper('role')->nameToAlias('GUEST');
        $this->redirect('/acesso/login');
    }

}
